<template>
  <el-container class='elheight'>
    <el-aside class='appTree'>
      <app-tree :tree-data="treeData" v-on:appTreeClick="appTreeClick"></app-tree>
    </el-aside>
    <el-main>
      <el-container>
        <el-header class="dzy-main-header">
          <div class="btn-group-el">
            <btn-group :currentSelectedData="currentSelectedData" @btnClickCallback="btnClickCallback"></btn-group>
          </div>
          <div class="dzy-custom-search-box">
            <div>
              被实施主体名称：<el-input placeholder="请输入内容" v-model="selectForm.name" clearable class="dzy-custom-input"></el-input>
            </div>
            <div>
              被实施主体层级：
              <el-select v-model="selectForm.implementedLevel" clearable placeholder="请选择">
                <el-option v-for="(item,index) in orgLevelOption" :key="index" :label="item.name" :value="item.code"></el-option>
              </el-select>
            </div>
            <div>
              实施主体名称：<el-input placeholder="请输入内容" v-model="selectForm.mainBodyName" clearable class="dzy-custom-input"></el-input>
            </div>
            <div>
              实施主体层级：
              <el-select v-model="selectForm.mainBodyLevel" clearable placeholder="请选择">
                <el-option v-for="(item,index) in orgLevelOption" :key="index" :label="item.name" :value="item.code"></el-option>
              </el-select>
            </div>
            <div>
              政策种类：
              <el-select v-model="selectForm.policyType" clearable filterable placeholder="请选择">
                <el-option v-for="(item,index) in policyTypesOption" :key="index" :label="item.name" :value="item.code"></el-option>
              </el-select>
              <el-button @click="searchHandleClick" type="primary" icon="el-icon-search">查询</el-button>
            </div>
          </div>
        </el-header>
        <el-main>
          <app-table
            :page-data="pageData"
            :table-columns="tableColumns"
            v-on:currentChange="handleCurrentChange"
            v-on:handleCheckedRows="handleCheckedRows">
          </app-table>
          <el-dialog :title="dialogTitle" :visible.sync="dialogFormVisible" class="custom-dialog_style_twoLine" :before-close="cancel" :close-on-click-modal="false">
            <el-form :model="formData"
                     :rules="rules"
                     ref="formData"
                     :disabled="showOnly"
                     label-width="50%">
              <el-form-item label="被实施地区：" prop="regionIdArr">
                <div class="block">
                  <el-cascader
                    placeholder="请选择"
                    :options="regionOptions"
                    filterable
                    clearable
                    change-on-select
                    :props="areaProps"
                    v-model="formData.regionIdArr">
                  </el-cascader>
                </div>
              </el-form-item>
              <el-form-item label="被实施地区层级：" prop="implementedLevel" label-width="30%">
                <el-select v-model="formData.implementedLevel" clearable placeholder="请选择">
                  <el-option v-for="(item,index) in orgLevelOption" :key="index" :label="item.name" :value="item.code"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="实施主体名称：" prop="mainBodyName" label-width="30%">
                <el-input v-model="formData.mainBodyName" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="实施主体层级：" prop="mainBodyLevel" label-width="30%">
                <el-select v-model="formData.mainBodyLevel" clearable placeholder="请选择">
                  <el-option v-for="(item,index) in orgLevelOption" :key="index" :label="item.name" :value="item.code"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="政策种类：" prop="policyType" label-width="30%">
                <el-select v-model="formData.policyType" clearable filterable placeholder="请选择">
                  <el-option v-for="(item,index) in policyTypesOption" :key="index" :label="item.name" :value="item.code"></el-option>
                </el-select>
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer" v-if="isfooterBtnShow">
              <el-button @click="cancel">取 消</el-button>
              <el-button type="primary" @click="save('formData')">确 定</el-button>
            </div>
          </el-dialog>
        </el-main>
      </el-container>
    </el-main>
  </el-container>
</template>

<script>
import AppTree from '@/components/common/AppTree'
import AppTable from '@/components/AppTable'
import BtnGroup from '@/components/BtnGroup'
import {getAllRegion} from '@/utils/region'
import {getRegionTree} from '@/http/AppApi'
import {getDictDataOption} from '@/utils/getDictDataOption'
import {findLeaderDuty, createLeaderDuty, updateLeaderDuty, delLeaderDuty} from '@/http/OrgApi'
export default {
  data () {
    return {
      dialogFormVisible: false,
      isfooterBtnShow: true,
      pageData: {},
      treeData: [],
      dialogTitle: '',
      currentSelectedData: [],
      showOnly: false,
      tableColumns: [
        { prop: 'name', label: '被实施主体名称' },
        { prop: 'implementedLevel', label: '被实施地区层级', formatter: this.orgLevelFormatter },
        { prop: 'mainBodyName', label: '实施主体名称' },
        { prop: 'mainBodyLevel', label: '实施主体层级', formatter: this.orgLevelFormatter },
        { prop: 'policyType', label: '政策种类', formatter: this.mainBodyLevelFormatter }
      ],
      tableDada: [],
      regionOptions: [],
      formData: {},
      selectForm: {},
      areaProps: {
        label: 'name',
        value: 'id'
      },
      rules: {
        policyType: [
          { required: true, message: '请选择政策种类：', trigger: 'blur' }
        ],
        mainBodyLevel: [
          { required: true, message: '请选择实施主体层级', trigger: 'blur' }
        ],
        mainBodyName: [
          { required: true, message: '请输入实施主体名称', trigger: 'blur' }
        ],
        implementedLevel: [
          { required: true, message: '请选择被实施地区层级', trigger: 'blur' }
        ],
        regionIdArr: [
          { type: 'array', required: true, message: '请选择被实施地区', trigger: 'blur' }
        ]
      },
      orgLevelOption: [],
      policyTypesOption: []
    }
  },
  components: {
    AppTree,
    BtnGroup,
    AppTable
  },
  mounted () {
    this.policyTypesOption = getDictDataOption('政策种类')
    getRegionTree().then(resp => {
      if (resp.code && resp.code === '200') {
        this.treeData = resp.data
        this.regionOptions = resp.data
      } else {
        this.$message({
          type: 'info',
          message: resp.message
        })
        return ''
      }
    })
    this.getTableData()
    this.orgLevelOption = getDictDataOption('层级')
  },
  methods: {
    // 格式化层级
    orgLevelFormatter (row, column) {
      let orgLevelOption = getDictDataOption('层级')
      let resorgLevel = ''
      let property = column.property
      for (let i = 0; i < orgLevelOption.length; i++) {
        if (orgLevelOption[i].code === row[property]) {
          resorgLevel = orgLevelOption[i].name
          break
        }
      }
      return resorgLevel
    },
    // 格式化政策种类
    mainBodyLevelFormatter (row, column) {
      let policyTypesOption = getDictDataOption('政策种类')
      let policyType = ''
      for (let i = 0; i < policyTypesOption.length; i++) {
        if (policyTypesOption[i].code === row.policyType) {
          policyType = policyTypesOption[i].name
          break
        }
      }
      return policyType
    },
    save (formName) {
      this.$refs[formName].validate((valid) => {
        if (!valid) {
          this.$alert('请填写正确表单格式', '', {
            confirmButtonText: '确定'
          })
          return ''
        } else {
          if (this.formData.regionIdArr) {
            let regionIdIndex = this.formData.regionIdArr.length - 1
            this.formData.regionId = this.formData.regionIdArr[regionIdIndex]
          }
          if (this.formData.id) {
            updateLeaderDuty(this.formData).then(resp => {
              if (resp.code && resp.code === '200') {
                this.dialogFormVisible = false
                this.$message({
                  type: 'success',
                  message: '修改成功'
                })
                this.getTableData()
              } else {
                this.$message({
                  type: 'info',
                  message: resp.message
                })
              }
            })
          } else {
            createLeaderDuty(this.formData).then(resp => {
              if (resp.code && resp.code === '200') {
                this.dialogFormVisible = false
                this.$message({
                  type: 'success',
                  message: '添加成功'
                })
                this.getTableData()
              } else {
                this.$message({
                  type: 'info',
                  message: resp.message
                })
              }
            })
          }
        }
      })
    },
    del (rows) {
      if (rows && rows instanceof Array && rows.length > 0) {
        this.$confirm('此操作将永久删除, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          rows.forEach(row => {
            delLeaderDuty(row).then(resp => {
              if (resp.code && resp.code === '200') {
                this.$message({
                  type: 'success',
                  message: '删除成功'
                })
                this.getTableData()
              } else {
                this.$message({
                  type: 'info',
                  message: resp.message
                })
              }
            })
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      }
    },
    cancel () {
      this.dialogFormVisible = false
      this.formData = {}
    },
    getTableData (param) {
      findLeaderDuty(param).then(resp => {
        if (resp.code && resp.code === '200') {
          this.pageData = resp.data
          if (this.pageData.items && this.pageData.items instanceof Array) {
            this.tableData = this.pageData.items
          }
        } else {
          this.$message({
            type: 'info',
            message: resp.message
          })
          return ''
        }
      })
    },
    handleCurrentChange (val) {
      this.selectForm.offset = (val - 1) * 10
      this.getTableData(this.selectForm)
    },
    btnClickCallback (callbackData) {
      if (callbackData.btnType === 'delete') {
        this.dialogFormVisible = false
        let rows = callbackData.rows
        this.del(rows)
      } else {
        this.isfooterBtnShow = callbackData.btnType !== 'get'
        if (callbackData.btnType === 'post') {
          this.dialogTitle = '新增'
          if (this.formData.regionIdArr) {
            let arr = this.formData.regionIdArr
            this.formData = {}
            this.formData.regionIdArr = arr
          } else {
            this.formData = {}
          }
        } else {
          this.dialogTitle = callbackData.btnType === 'put' ? '修改' : '查看'
          let obj = {}
          obj = JSON.stringify(callbackData.rows[0])
          this.formData = JSON.parse(obj)
          let regionData = {}
          regionData.id = this.formData.regionId
          regionData.items = this.regionOptions
          this.formData.regionIdArr = getAllRegion(regionData)
        }
        this.showOnly = callbackData.sohwOnly
        this.dialogTitle = callbackData.dialogTitle
        this.dialogFormVisible = true
      }
    },
    handleCheckedRows (rows) {
      if (rows && rows instanceof Array && rows.length > 0) {
        this.currentSelectedData = rows
        this.formData = rows[0]
      } else if (rows.length === 0) {
        this.currentSelectedData = []
      }
    },
    appTreeClick (data) {
      let regionData = {}
      regionData.id = data.id
      regionData.items = this.regionOptions
      this.formData.regionIdArr = getAllRegion(regionData)
      this.selectForm.regionId = data.id
      this.selectForm.offset = 0
      this.getTableData(this.selectForm)
    },
    searchHandleClick () {
      this.selectForm.offset = 0
      this.getTableData(this.selectForm)
    }
  }
}
</script>
